<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:公共接口
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\Api;
use app\ApiController;
use DtApp\AliYun\aliyun\OssService;
use support\Request;
use think\facade\Db;

class CommonController extends ApiController
{
    protected $noNeedLogin = ['docredit'];
    protected $noNeedRight = '*';

    /**
     * 上传文件，支持多文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */

    public function upload()
    {

        try {
            $cfg = [
                'image' => 'fileSize:10485760|fileExt:jpg,png,gif',
                'file'  => 'fileSize:10485760|fileExt:xls,xlsx,doc,docx,zip,rar',
            ];
            $file_type = request()->post("file_type");
            $by        = 2;
            if (!$cfg[$file_type]) {
                throw new \Exception("Invalid parameters");
            }

            // 获取表单上传文件
            $files    = request()->file();
            $file_cfg = $cfg[$file_type];

            $savename = [];
            $rule     = $this->analyzeFileRule($file_cfg);

            foreach ($files as $k => $file) {

                if (!in_array($file->getUploadExtension(), $rule['ext'])) {

                    throw new \Exception("file type error");

                }
                if ($file->getSize() > $rule['size']) {
                    throw new \Exception("file size error");
                }

            }

            foreach ($files as $k => $file) {

                $r = ['file_path' => $this->uploadAPi($by, $file_type, $file), 'file_name' => $file->getUploadName()];

                $r['created_time'] = time();

                $r['attach_id'] = Db::name("attach")->insertGetId($r);

                $savename[] = $r;
            }

            $res = count($savename) == 1 ? $savename[0] : $savename;

            return $this->success(__('Uploaded successful'), ['file' => $res]);
        } catch (\Exception $e) {

            return $this->error($e->getMessage());
        }

    }

    private function analyzeFileRule($rule)
    {
        $rule = explode("|", $rule);
        $size = substr($rule[0], 9);
        $ext  = substr($rule[1], 8);
        return ['size' => $size, 'ext' => explode(",", $ext)];
    }

    private function uploadApi($by, $file_type, $file)
    {

        switch ($by) {
            case 1:
                $f = $this->ossUpload($file_type, $file);
                break;

            default:
                $f = $this->localUpload($file_type, $file);
                break;
        }
        return $f;
    }

    private function ossUpload($file_type, $file)
    {

        return OssService::instance()->upload($file_type . '/' . date('Y-m-d') . '/' . time() . '_' . $file->getUploadName(), $file->getRealPath());

    }

    private function localUpload($file_type, $file)
    {

        $new_file = '/files/' . $file_type . '/' . date('Y-m-d') . '/' . time() . '_' . $file->getUploadName();

        $file->move(public_path() . $new_file);
        return $new_file;

    }

}
